package settingsapp.ui.panel;

import java.util.Arrays;

import settingsapp.settings.ClickableSettingChanger;
import settingsapp.settings.continuous.ContinuousSettingFactory;
import settingsapp.settings.toggle.ToggleSettingFactory;
import settingsapp.ui.PanelGridActivity;
import android.util.AttributeSet;
import android.util.Log;
import android.widget.Button;

public abstract class Panel extends Button
{
	protected PanelGridActivity context;
	ClickableSettingChanger changer;		// object to control the settings
	
	protected String name = "";
	
	private static final String TAG = Panel.class.getSimpleName();

	/**
	 * Called after Button's default constructors to
	 * initialize all custom aspects
	 */
	abstract protected void init();
	
	public Panel(PanelGridActivity context)
	{
		super(context);
		this.context = context;
		init();
	}

	public Panel(PanelGridActivity context, AttributeSet attrs)
	{
		super(context, attrs);
		this.context = context;
		init();
	}

	public Panel(PanelGridActivity context, AttributeSet attrs, int defStyle)
	{
		super(context, attrs, defStyle);
		this.context = context;
		init();
	}
	
	abstract public Runnable getClickAction();
	
	/**
	 * Displays a dialog with the different settings
	 * options for this Panel, setting the panel type 
	 * when one is selected
	 */
	abstract public void showSetTypeDialog();
	
	/**
	 * A panel is defined by its changer
	 * This String can be used to write the object to file
	 */
	public String toString()
	{
		return changer.toString();
	}
	
	public static Panel fromString(PanelGridActivity context, String panelString)
	{
		Log.d(TAG, "Parsing " + panelString);
		String[] tokens = panelString.split("\\.");
		removeNonNumeric(tokens);
		
		Log.d(TAG, "tokens.length = " + tokens.length);
		Log.d(TAG, "tokens[0].length = " + tokens[0].length());
		Log.d(TAG, "tokens[1].length = " + tokens[1].length());
		Log.d(TAG, Arrays.toString(tokens));
		return fromString(context, Integer.parseInt(tokens[0]), Integer.parseInt(tokens[1]));
	}
	
	private static void removeNonNumeric(String[] strings)
	{
		for (int i = 0; i < strings.length; i++)
		{
			String oldString = strings[i];
			
			StringBuilder newString = new StringBuilder();
			for (int j = 0; j < oldString.length(); j++)
			{
				char cur = (oldString.charAt(j));
				if (Character.isDigit(cur))
					newString.append(cur);
			}
			
			strings[i] = newString.toString();
		}
	}
	
	private static Panel fromString(PanelGridActivity context, int mainSettingType, int settingIndex)
	{
		TogglePanel newPanel = new TogglePanel(context);
		newPanel.setSettingType(mainSettingType, settingIndex);
		
		return newPanel;
	}
}
